package com.webdemo07.service.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.webdemo07.pojo.User;
import com.webdemo07.service.UserService;
import com.webdemo07.util.SpringHandler;

public class UserServiceImpl implements UserService {
	private Connection conn;
	private PreparedStatement pstmt = null;
	private ResultSet rs = null;

	@Override
	public void addUser(User user) {
		conn = SpringHandler.newInstance().getConnection();
		String sql = "insert into xml18_webdemo07(id,name) values(?,?)";
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, user.getId());
			pstmt.setString(2, user.getName());
			pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void deleteUser(int id) {
		conn = SpringHandler.newInstance().getConnection();
		String sql = "delete from xml18_webdemo07 where id=?";
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, id);
			pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void updateUser(User user) {
		conn = SpringHandler.newInstance().getConnection();
		String sql = "update xml18_webdemo07 set name=? where id=?";
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, user.getName());
			pstmt.setInt(2, user.getId());
			pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<User> queryUser() {
		List<User> users = new ArrayList<User>();
		User user = null;
		conn = SpringHandler.newInstance().getConnection();
		String sql = "select id,name from xml18_webdemo07";
		try {
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				user = new User();
				user.setId(rs.getInt("id"));
				user.setName(rs.getString("name"));
				users.add(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return users;
	}

	@Override
	public User getUser(int id) {
		User user = null;
		conn = SpringHandler.newInstance().getConnection();
		String sql = "select id,name from xml18_webdemo07 where id=?";
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, id);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				user = new User();
				user.setId(rs.getInt("id"));
				user.setName(rs.getString("name"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return user;
	}

}
